package com.example.wan_android_flutter

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import com.jing.camera_plugin.CameraPlugin

class MainActivity : FlutterActivity() {

    private val CHANNEL = "camera_plugin"
    private var cameraPlugin: CameraPlugin? = null

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        cameraPlugin = CameraPlugin(this)

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "takePicture") {
                cameraPlugin?.takePicture(object : CameraPlugin.CameraResultCallback {
                    override fun onSuccess(bitmap: Bitmap) {
                        // 将图片保存并返回路径
                        val path = CameraPlugin.saveBitmapToFile(this@MainActivity, bitmap, "photo.jpg")
                        result.success(path)
                    }

                    override fun onError(exception: Exception) {
                        result.error("CAMERA_ERROR", exception.message, null)
                    }
                })
            } else {
                result.notImplemented()
            }
        }
    }

    // 必须传递权限结果
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        cameraPlugin?.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    // 传递拍照返回数据
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        cameraPlugin?.onActivityResult(requestCode, resultCode, data!!)
    }
}
